<template>
  <div class="setlease">
    <hunk-head :icon="icons" :name="names"></hunk-head>
    <div class="leaseform">
      <uni-forms ref="form" :modelValue="formData">
        <!-- <uni-forms-item label="房屋地址" name="address" :label-width="120" class="item1">
          <div class="address">{{address}}</div>
        </uni-forms-item> -->
        <div class="housAdd">
            <div class="lable">房屋地址</div>
            <div class="address">{{address}}</div>
          </div>
        <div style="height:10px;background:#F9F9F9;"></div>
        <!-- <uni-forms-item name="leasetype" label="租约方式" :label-width="120">
          <uni-data-checkbox selectedColor="#FFBD6C" selectedTextColor="#4A4A4A" v-model="formData.leasetype" :localdata="leaseMode" />
        </uni-forms-item> -->
        
        <uni-forms-item name="payrenttype" label="交租方式" :label-width="120">
          <uni-data-checkbox selectedColor="#FFBD6C" selectedTextColor="#4A4A4A" v-model="formData.payrenttype" :localdata="payMode"/>
        </uni-forms-item>

        <uni-forms-item v-if="formData.tenantname" label="租客姓名" name="tenantname" :label-width="120">
          <!-- <uni-easyinput disabled type="text" :inputBorder="false" v-model="formData.tenantname" placeholder="请输入租客姓名" /> -->
          <div class="cont">{{formData.tenantname}}</div>
        </uni-forms-item>

        <uni-forms-item v-if="formData.cardid" label="身份证号码" name="cardid" :label-width="120">
          <!-- <uni-easyinput disabled type="text" :inputBorder="false" v-model="formData.cardid" placeholder="请输入租客身份证号码" /> -->
          <div class="cont">{{formData.cardid}}</div>
        </uni-forms-item>

        <uni-forms-item label="租金（元/月）" name="rent" :label-width="120">
          <!-- <uni-easyinput disabled type="number" :inputBorder="false" v-model="formData.rent" placeholder="请输入租金金额，建议租金800元" /> -->
          <div class="cont">{{formData.rent}}</div>
        </uni-forms-item>

        <uni-forms-item label="履约保证金（元/月）" name="mortgage" :label-width="170">
          <!-- <uni-easyinput disabled type="number" :inputBorder="false" v-model="formData.mortgage" placeholder="请输入最低押金数字" /> -->
          <div class="cont">{{formData.mortgage}}</div>
        </uni-forms-item>

        <uni-forms-item label="租约开始时间" name="starttime" :label-width="120">
            <div class="cont">{{(formData.starttime).split(' ')[0]}}</div>
        </uni-forms-item>

        <uni-forms-item label="租约结束时间" name="endtime" :label-width="120">
            <div class="cont">{{formData.endtime}}</div>
        </uni-forms-item>
        <uni-forms-item label="交租周期" name="endtime" :label-width="120">
            <div class="cont">{{getCycleName(formData.cycle)}}</div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.dailyrent&&formData.cycle==5" label="日付租金" name="endtime" :label-width="120">
            <div class="cont">{{formData.dailyrent}}元/日</div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.weeklyrent&&formData.cycle==5" label="周付租金" name="endtime" :label-width="120">
            <div class="cont">{{formData.weeklyrent}}元/周</div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.monthlyrent&&formData.cycle==5" label="月付租金" name="endtime" :label-width="120">
            <div class="cont">{{formData.monthlyrent}}元/月</div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.quarterlyrent&&formData.cycle==5" label="季付租金" name="endtime" :label-width="120">
            <div class="cont">{{formData.quarterlyrent}}元/三个月</div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.cycle==5" label="管理费率" name="endtime" :label-width="120">
            <div class="cont">{{formData.rate}}%</div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.cycle==5" label="首次交租采用费率" name="rate" :label-width="140">
            <div class="cont">{{isva(formData.firstrentpayment)}}</div>
        </uni-forms-item>
        <uni-forms-item  v-if="formData.cycle==5" label="首次交租时长" name="firstrentpaymentday" :label-width="120">
            <div class="cont">{{formData.firstrentpaymentday}}
              <span>{{unit}}</span>
            </div>
        </uni-forms-item>
        <uni-forms-item v-if="formData.cycle==5" label="电费" name="electricityfees" :label-width="120">
            <div class="cont">{{formData.electricityfees}}元/度</div>
        </uni-forms-item>



        <div style="height:10px;background:#F9F9F9;"></div>
        <!-- <uni-forms-item name="cycle" label="交租周期" :label-width="120" class="cycleItme">
          <uni-data-checkbox selectedColor="#FFBD6C" selectedTextColor="#4A4A4A" v-model="formData.cycle" :localdata="paycycle"/>
        </uni-forms-item> -->

        <uni-forms-item label="提前交租时间" name="advancetime" :label-width="140">
          <!-- <uni-easyinput disabled type="number" :inputBorder="false" v-model="formData.advancetime" placeholder="请填写需要提前交租的时间" /> -->
          <div class="cont">{{formData.advancetime}}天</div>
        </uni-forms-item>

        <uni-forms-item v-if="formData.econtractid" label="已签订的电子合同"  :label-width="130">
            <div class="cont" @click="getPdfDetail" :style="{color:formData.econtractid?'#0191FF':'#999','fontSize':'30rpx',fontWeight:'800','lineHeight':'44px'}">{{formData.code?formData.code:'未关联电子合同'}} > </div>
        </uni-forms-item>

        <!-- <div style="height:10px;background:#F9F9F9;"></div>
        <div class="cotrant" @click="goContract">
              <div :style="{color:'#333','fontSize':'30rpx','fontWeight':800}">关联电子合同</div>
              <div :style="{color:formData.eid?'#0191FF':'#999','fontSize':'30rpx',fontWeight:'800'}">{{formData.code?formData.code:'请选择关联的电子合同'}}</div>
        </div> -->


      </uni-forms>
      <div class="btn" v-if="!souse">
        <button class="subBtn" @click="submit(1)">确认</button>
        <button class="backBtn" @click="submit(5)">取消</button>
      </div>
      
    </div>
      <uni-popup ref="popup1" type="center">
      <div class="tips1">
        <div class="tips-top">认证授权</div>
        <div class="tips-text">尊敬的用户，您还未进行实名认证，是否进行实名认证</div>
        <div class="tips-btn">
          <div class="btn-closs" @click="closePopup1">取消</div>
          <div  @click="gorenzheng">确认</div>
        </div>
      </div>
    </uni-popup>
    <uni-popup ref="approve" type="center">
      <div class="tips2">
        <div class="tips-top">提示</div>
        <div class="tips-text">尊敬的用户，您还未进行用户授权，是否进行用户授权？</div>
        <div class="tips-btn">
          <div class="btn-closs" @click="closeP">取消</div>
          <div  @click="checkedP">确认</div>
        </div>
      </div>
    </uni-popup>
  </div>
</template>

<script>
import Head from '@componentsMine/head'
import { confirmcontract, getContract } from '@/apis/housesInfo'
import store from '@store/index'
import {GetUserInfo_openid,getuseropenid,createPayment} from '@/apis/user'
import{tEContractInfo} from '@/apis/contract'
import { setToken } from '@utils/auth'
import {debounce} from 'lodash'

export default {
  components: {
    'hunk-head': Head
  },

  data() {
    return {
      icons: 'home',
      names: '租约确认',
      unit:'',
      payMode: [{"value": 0,"text": "线上交租","disable":true },{"value": 1,"text": "线下交租","disable":true}],
      paycycle: [
        {"value": 0,"text": "月付","disable":true},
        {"value": 1,"text": "两月付","disable":true},
        {"value": 2,"text": "季付","disable":true},
        {"value": 3,"text": "半年","disable":true},
        {"value": 4,"text": "年付","disable":true}
      ],
      formData: {
        tenantname: '',
        leasetype: 0,
        payrenttype: 1,
        cardid: '',
        rent: '',
        mortgage: '',
        starttime: '',
        endtime: '',
        cycle: 2,
        advancetime: ''
      },
      houseinfo:null,
      wid:null,
      address:'',
      souse:null
    }
  },
  onLoad(e){
    console.log(88,e)
    // this.houseinfo = JSON.parse(e.query)
    this.wid = e.wid
    this.getContract(e.wid)
    if(e.souse){
      this.souse = e.souse
      this.icons = 'back'
      this.names = '租约详情'
    }else{
      this.icons = 'home'
      this.names = '租约确认'
      this.isShouquan()
    }
  },
  computed:{
    userInfo(){
      return this.$store.state.baseStore.userInfo
    }, baseUrl() {
      return process.env.VUE_APP_BASE_IMG_URL;
    },
    isva(){
      return(value) => {
          switch (Number(value)) {
              case 0:
                return '按日'
              case 1:
                return '按周'
              case 2:
                return '按月'
              case 3:
                return '按季度'
          }
      }
    
    },
    getCycleName(){
      return (news)=>{
          switch (Number(news)) {
            case 0:
              return '按月'
            case 1:
              return '两月付'
            case 2:
              console.log(news)
              return '季付'
            case 3:
              return '半年付'
            case 4:
              return '年付'
            default :
              return '灵活交租'
          }
      }
      
    }
  },
  methods: {
    getPdfDetail:debounce(function(){
      let eid = this.formData.econtractid
         uni.showLoading({
          title: '加载中...'
      })
          tEContractInfo({
            eid:eid
          }).then(e=>{
            uni.downloadFile({
              url: e.data.fileurl,
              success:(res)=> {
                var filePath = res.tempFilePath;
                this.pdfPath = filePath
                uni.openDocument({
                  filePath: filePath,
                  showMenu: true,
                  success:(res) =>{
                    uni.hideLoading()
                    this.isRead = true
                    console.log('打开文档成功');
                  }
                });
              }
            });
          })
    },1000),
    checkedP(){
      this.$refs.approve.close()
      uni.navigateTo({ url: '/subPackage/link/approve' })
    },
    closeP(){
      this.$refs.approve.close()
      uni.reLaunch({ url: '/pages/login/checkUser' })
    },
    closePopup1(){
      this.$refs.popup1.close()
    },
    gorenzheng(){
      this.$refs.popup1.close()
      uni.navigateTo({ url: '/subPackage/link/renzheng' })
      // this.$jump({path:'/pages/link/renzheng'})
    },
    submit:debounce(function(int){
       console.log(88,this.userInfo.userid)
      // if(!this.userInfo.cardid){
      //   this.$refs.popup1.open()
      //   return
      // }
      let user = this.$store.state.baseStore.userInfo
      if(!user.userid){
        this.$refs.approve.open()
        return
      }
      let data = {
        confirmuserid: user.userid,
        state: int,
        wid: this.wid
      }
      console.log(99+"data",data,'this.userInfo',this.userInfo)
      confirmcontract(data).then(res =>{
        if(res.code == 200){
          if(int == 5){
            uni.redirectTo({ url: '/pages/index/index' })
          }else{
            uni.showToast({
              title: '合同确认成功',
              success:()=>{
                 if(+this.formData.payrenttype==0){
                    this.pay(res.data.orderno,res.data.payprice) 
                  }else{
                    uni.redirectTo({ url: '/pages/index/index' })
                  }
              }
            })
          }
        }else{
          uni.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      })
    },1000),
     pay(orderno,payprice) {
          const openid = wx.getStorageSync('openid')
            createPayment({
                goods_desc:"房屋交租",
                goods_title:'房屋交租',
                openid,
                orderno,
                payamt:payprice
            }).then(res => {
              console.log(res)
                 if(res.code == '500'){
                  uni.showToast({
                    title: res.msg,
                    icon: 'none'
                  })
                  return
                }
                const {timeStamp,nonceStr,package:pack,paySign,signType} = JSON.parse(res.data.expend.pay_info) // {"appId":"wx30089e25b0b08834","timeStamp":"1652080266","nonceStr":"a4ddb132cfa24ca28816004e020b6c9d","package":"prepay_id=wx09151106543230e69e5d8298b2a13f0000","signType":"RSA","paySign":"ybY1brgTSRiOK/LOcxWk0mEeCXxPd9Hhlxt/IM/xmLe11bTu/CTXJPrRAVw/jX1FRz4eFyo01UTAxgdS9m3P+VwK1RO3XFp37yc5kiIcNp9CmrdpqXM1ACFy1AfkQmOPm9xul1eh5Sduzjw8F6Xyv10vPKOBKzVlzv3sMSEIXrxg9aT+imsm3TWT9ew+M1FvEyNKQ8VAgckJjXijFnjgfXc5H6jxHwDbtafKKw2kd6/2/qcutd9OWG2jJPJxrh7/9Wo3FGEceldpceiXt6w/I60yxefdGs9mSD/S+AKP5xGWnuLWW9SurEA0envA+LS8hlzaeRTadmLmLYkDeEdjxg=="}
                // const {timeStamp,nonceStr,package:pack,paySign} = JSON.parse(res.data.expend.pay_info)
                console.log(timeStamp,nonceStr,pack,paySign,signType)
                wx.requestPayment(
                    {
                        timeStamp,
                        nonceStr,
                        package:pack,
                        signType,
                        paySign,
                        'success':function(res){
                            uni.showToast({
                              title: res.msg,
                              icon: '支付成功'
                            })
                          uni.redirectTo({ url: '/pages/index/index' })
                        },
                        'fail':function(res){},
                        'complete':function(res){}
                    })
            })
        },
    getContract(wid){
      let that = this
      getContract({wid: wid}).then(res=>{
        if( res.code == 200 ){
          console.log(res.data.firstrentpayment)
          if(res.data.firstrentpayment == '0'){
            this.unit = '日'
          }else if(res.data.firstrentpayment == '1'){
            this.unit = '周'
          }else if(res.data.firstrentpayment == '2'){
            this.unit = '月'
          }else if(res.data.firstrentpayment == '3'){
            this.unit = '季度'
          }
          that.$nextTick(()=>{
            let arr1 = res.data.starttime.split(' ')
            that.formData.starttime = arr1[0]
            let arr = res.data.endtime.split(' ')
            that.formData = res.data
            that.formData.endtime = arr[0]
            // that.formData.tenantname = res.data.tenantname
            // that.formData.leasetype = res.data.leasetype
            // that.formData.payrenttype = res.data.payrenttype
            // that.formData.cardid = res.data.cardid
            // that.formData.rent = res.data.rent
            // that.formData.mortgage = res.data.mortgage
            // that.formData.cycle = res.data.cycle
            // that.formData.advancetime = res.data.advancetime
            // that.formData.econtractid = res.data.econtractid
            // that.formData.code = res.data.code
            that.address = res.data.address
            that.$forceUpdate()
          })
        }else{
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    },
    isShouquan(){
      let that = this
      wx.login({
        success:(res)=> {
          console.log('login',res)
          var code = res.code
          getuseropenid({code}).then(e=>{
            console.log('getuseropenid',typeof(e.data.openid),e.data.openid)
            // if(e.data.openid != 'null'){
              wx.setStorageSync('openid', e.data.openid)
              wx.setStorageSync('session_key', e.data.session_key)
              GetUserInfo_openid({openid:e.data.openid}).then(e=>{
                console.log('执行GetUserInfo_openid',e)
                that.isCode = true
                if(e.code == 200){
                  store.commit('baseStore/SET_USERINFO', e.data)
                  setToken(e.data.token)
                }else if(e.code == 300){
                  that.$refs.approve.open()
                }
              }).catch(e=>{
                
              })
            // }else{
            //   that.isCode = false
            //   that.$refs.wxpopup.open()
            // }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.setlease {
  width: 100vw;
  box-sizing: border-box;
  height: 100vh;
  background: #F9F9F9;
  display: flex;
  flex-direction: column;
  .leaseform{
    flex: 1;
    overflow-y: auto;
    .btn{
      display: flex;
      flex-direction: column;
      justify-items: center;
      align-items: center;
      font-size: 16px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      line-height: 45px;
      padding-bottom: 40px;
      .subBtn{
        margin-top: 16px;
        width: 345px;
        height: 45px;
        background: linear-gradient(315deg, #FFAA58 0%, #FFBD6C 100%);
        box-shadow: 0px 2px 4px 0px rgba(252, 174, 55, 0.21), 0px 3px 5px 0px rgba(255, 216, 111, 0.14);
        border-radius: 100px;
        text-shadow: 0px 2px 4px rgba(252, 174, 55, 0.21);
        color: #FFFFFF;
      }
      .backBtn{
        margin-top: 10px;
        width: 345px;
        height: 45px;
        border-radius: 100px;
        border: 1px solid #FFBD6C;
        color: #FFAA58;
      }
      button::after{
        border:0
      }
    }
    
  }
  .tips1{
    width: 335px;
    height: 174px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 10px;
    background-color: #fff;
    position: relative;
    .tips-top{
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #4A4A4A;
      line-height: 22px;
      margin-top: 20px;
    }
    .tips-text{
      margin: 20px 0;
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #6D7278;
      line-height: 22px;
      padding: 0 20px;
      text-align: center;
    }
    .tips-btn{
      width: 100%;
      border-top: 2px solid #EFEFEF;
      display: flex;
      position: absolute;
      bottom: 0;
      div{
        height: 40px;
        width: 50%;
        font-size: 13px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #4A4A4A;
        line-height: 40px;
        text-align: center;
      }
      .btn-closs{
        border-right: 2px solid #EFEFEF;
      }
    }
  }
}
.tips2{
    width: 335px;
    height: 174px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 10px;
    background-color: #fff;
    position: relative;
    .tips-top{
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #4A4A4A;
      line-height: 22px;
      margin: 20px 0 30px 0;
    }
    .tips-text{
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #6D7278;
      padding: 0 20px;
      line-height: 22px;
    }
    .tips-btn{
      width: 100%;
      border-top: 2px solid #EFEFEF;
      display: flex;
      position: absolute;
      bottom: 0;
      div{
        height: 40px;
        width: 50%;
        font-size: 13px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #4A4A4A;
        line-height: 40px;
        text-align: center;
      }
      .btn-closs{
        border-right: 2px solid #EFEFEF;
      }
    }
  }

::v-deep .uni-forms{
  background: #FFFFFF;
  .uni-forms-item{
    // height: 45px;
    margin: 0 15px;
    background: #FFFFFF;
    border-bottom: 1px solid #EFEFEF;
    .uni-forms-item__box{
      .uni-error-message{
        right: 0;
        left: auto;
        .uni-error-message-text{
          line-height: 10px;
          font-size: 10px;
        }
      }
      .uni-forms-item__inner{
        margin: 0;
        padding: 0;
      }
    }
    
    .uni-forms-item__label{
      padding: 0;
      height: 45px;
      .label-text{
        font-size: 15px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #000000;
        line-height: 21px;
      }
    }
    .uni-forms-item__content{
      height: 45px;
      text-align: right;
      .uni-data-checklist{
        margin-bottom: 6px;
        height: 33px;
        .checklist-group{
          height: 100%;
          justify-content: flex-end;
          font-size: 14px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #4A4A4A;
          line-height: 35px;
          .checklist-box{
            position: static;
            margin: 0;
            margin-right: 20px;
          }
          .checklist-box:last-child{
            margin-right: 0;
          }
        }
      }
      .uni-easyinput{
        .uni-easyinput__content{
          .uni-easyinput__content-input{
            height: 45px;
            text-align: right;
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            line-height: 45px;
            color: #4A4A4A;
            .uni-easyinput__placeholder-class{
              font-size: 14px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 500;
              line-height: 45px;
              color: #9B9B9B;
              
            }
          }
        }
      }
      .uni-date{
        .uni-date-editor{
          div{
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #9B9B9B;
            line-height: 45px;
          }
        }
      }
      .address{
        height: 45px;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #4A4A4A;
        line-height: 45px;
      }
    }
  }
  .uni-forms-item:last-child{
    border: 0;
  }
  .housAdd{
    display: flex;
    justify-content: space-between;
    padding: 12px 15px;
    .lable{
      width: 150px;
      height: 21px;
      font-size: 15px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #000000;
      line-height: 21px;
    }
    .address{
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #4A4A4A;
      line-height: 20px;
    }
  }
  .item1{
    border: 0;
  }
  .cycleItme{
    height: auto;
    .is-direction-left{
      flex-direction: column;
      .uni-forms-item__label{
        height: auto;
        margin-top: 13px;
      }
      .uni-forms-item__content{
        height: auto;
        .checklist-group{
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
}
.cont{
  line-height: 45px;
}
</style>
